#!groovy

@Library('jenkinslib@master') _

def dingmes  = new org.devops.ding()
def tools = new org.devops.tools()
//代码作者
def Author = ''
//更新记录(3条)
def ChangeLog = ''
//gitlab仓库地址
String srcUrl = "${env.srcUrl}"
srcUrl = srcUrl.split("\\(")[0].trim()
//仓库分支
String branchName = "${env.branchName}"
//项目名称
String proJectname = "${env.project}"
//pipeline
pipeline{
    agent any    
    stages{

       stage("拉取代码"){
            steps{
                script{
                        workdir = srcUrl.split('/')[-1].split('.git')[0]
                        if(!workdir) {
                            println "获取工作目录失败"
                            exit()
                        }
                        tools.PrintMes("Clone代码","green")
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                        doGenerateSubmoduleConfigurations: false, 
                        extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "${workdir}"]], 
                        submoduleCfg: [], 
                        userRemoteConfigs: [[credentialsId: '347d036f-1dbb-4869-bbea-fcf4576b0ba0', url: "${srcUrl}"]]])
                        //代码作者
                        res = sh returnStdout: true ,script: "cd ${workdir} && git log -1|grep Author |awk '{print \$2}'"
                        Author = res.trim()
                        //更新记录(5条)
                        tmp_shell="""
                            cd ${workdir}
                            git log -3 |awk '!/^\$/' |awk '/^Author|^commit/ {next}{printf "%s\\n",\$0}'
                        """
                        res = sh returnStdout: true ,script: "${tmp_shell}"
                        ChangeLog = res.trim()
                }
            }
        }
        stage("编译打包"){
            steps{
                script{
                        tools.PrintMes("执行npm编译","green")
                        //清除已有dist文件
                        sh "cd ${workdir} && rm -rf dist"
                        sh "cd ${workdir} && rm -rf dist.tar.gz"
                        //编译
                        //修改前端环境变量

                        cmds="""
                            cd ${workdir}
                            sed -i 's/^VUE_APP_API_BASE_URL.*/VUE_APP_API_BASE_URL=http:\\/\\/61\\.143\\.60\\.85:8085/' .env
                            rm -rf dist
                            rm -rf dist.tar.gz
                            yarn install
                            yarn run buildApi
                            yarn run build
                            tar zcf dist.tar.gz dist
                        """
                        sh returnStdout: true ,script: "${cmds}"
                        //打包
                        sh "cd ${workdir} && tar zcf dist.tar.gz dist"
                    }
                }
            }
       //部署
       stage('SSH') {
            steps {
                script {                 
  	                def remote = [:]
  	                remote.name = 'wisdom_web'
  	                remote.host = '172.16.23.49'
                    remote.port = 22
                    remote.allowAnyHosts = true
                    withCredentials([usernamePassword(credentialsId: 'b0bcfa46-c887-4adf-bbda-861813f7c133', passwordVariable: 'password', usernameVariable: 'username')]) {
                        remote.user = "${username}"
                        remote.password = "${password}"
                    }
                    //删除旧数据
                    sshCommand remote: remote, command: "cd /aizhixin/frontend/wisdom/tar/ && rm -rf *"
                    //传输代码压缩包
                    //res = sh returnStdout: true ,script: "scp -o ProxyCommand='ncat --proxy-type http --proxy 61.143.60.85:8089 %h %p --proxy-auth aizhixin:Aizhixin@2021' ${workdir}/dist.tar.gz root@172.16.23.49:/aizhixin/frontend/wisdom/tar"
                    sshPut remote: remote, from: "${workdir}/dist.tar.gz", into: '/aizhixin/frontend/wisdom/tar'
                    //解压
                    sshCommand remote: remote, command: "cd /aizhixin/frontend/wisdom/tar && tar -xf dist.tar.gz"
                    //备份
                    sshCommand remote: remote, command: "cd /aizhixin/frontend/wisdom/web && mv * /aizhixin/frontend/wisdom/tar"
                    //删除
                    sshCommand remote: remote, command: "cd /aizhixin/frontend/wisdom/web && rm -rf *"
                    //替换
                    sshCommand remote: remote, command: "cd /aizhixin/frontend/wisdom/tar/dist && mv * /aizhixin/frontend/wisdom/web/"
                    //检查前端服务状态码
                    //sshCommand remote: remote, command: "curl -o /dev/null -s -w %{http_code} 127.0.0.1:8085"
                }
            }
       }
        //部署检测
        stage("deploy_check"){
            steps{
                script{
                    tools.PrintMes("检测服务状态","green")
                      //deployment status
                }
            }
        }
    }
        post{
            success{
                script{
                    tools.PrintMes("========pipeline executed successfully========",'green')
                    dingmes.HttpReq('1','null',"构建成功 ✅ ",Author,ChangeLog,'1')
                }
            }
            failure{
                script{
                    tools.PrintMes("========pipeline execution failed========",'red')
                    dingmes.HttpReq('1','null',"构建失败 ❌",Author,ChangeLog,'1',"请查看控制台")
                }
            }
            unstable{
                script{
                    tools.PrintMes("========pipeline execution unstable========",'red')
                    dingmes.HttpReq('1','null',"构建失败 ❌",Author,ChangeLog,'1',"不稳定异常")
                }
            }
            aborted{
                script{
                    tools.PrintMes("========pipeline execution aborted========",'blue')
                    dingmes.HttpReq('1','null',"构建失败 ❌",Author,ChangeLog,'1',"暂停或中断")
                }
            
        }
    }
}